<template>
  <div class="search-container">
    <div class="search-header">
      <div class="search-info">
        <h2 v-if="searchQuery">搜索结果："{{ searchQuery }}"</h2>
        <h2 v-else>搜索</h2>
        <p class="result-count" v-if="!loading && searchQuery">找到 {{ totalResults }} 个结果</p>
      </div>
      <div class="search-filters">
        <el-select v-model="sortBy" class="filter-select" @change="handleFilterChange">
          <el-option label="相关度" value="relevance" />
          <el-option label="上传时间" value="date" />
          <el-option label="观看次数" value="views" />
          <!-- <el-option label="评分" value="rating" /> -->
        </el-select>

        <el-select v-model="timeRange" class="filter-select" @change="handleFilterChange">
          <el-option label="全部时间" value="all" />
          <el-option label="最近一小时" value="hour" />
          <el-option label="今天" value="today" />
          <el-option label="本周" value="week" />
          <el-option label="本月" value="month" />
          <el-option label="今年" value="year" />
        </el-select>

        <el-select v-model="duration" class="filter-select" @change="handleFilterChange">
          <el-option label="任意时长" value="any" />
          <el-option label="短片 ( < 4分钟 )" value="short" />
          <!-- <el-option label="中片 ( 4-20分钟 )" value="medium" /> -->
          <el-option label="长片 ( > 20分钟 )" value="long" />
        </el-select>

       
      </div>
    </div>

    <div class="search-content">
      <!-- 搜索结果 -->
      <div class="search-results" v-loading="loading">
        <div v-if="results.length === 0 && !loading" class="empty-state">
          <el-empty :description="emptyDescription">
            <template #description>
              <p>{{ emptyDescription }}</p>
              <div class="search-tips" v-if="searchQuery">
                建议：
                <ul>
                  <li>请检查输入的文字是否正确</li>
                  <li>尝试使用其他搜索词</li>
                  <li>使用更常见的关键词</li>
                  <li>减少筛选条件</li>
                </ul>
              </div>
            </template>
          </el-empty>
        </div>

        <template v-else>
          <!-- 视频结果 -->
          <div class="video-results">
            <div v-for="video in results" :key="video._id" class="video-item" @click="goToVideo(video._id)">
              <div class="thumbnail">
                <img :src="video.thumbnail" :alt="video.title">
                <span class="duration">{{ formatDuration(video.duration) }}</span>
              </div>
              <div class="video-info">
                <h3 class="title">{{ video.title }}</h3>
                <div class="meta-info">
                  <div class="views-date">
                    <span>{{ formatViews(video.views) }}次观看</span>
                    <span class="dot">•</span>
                    <span>{{ formatDate(video.createdAt) }}</span>
                  </div>
                </div>
                <div class="channel-info">
                  <el-avatar :size="24" :src="video.user?.avatar">
                    <el-icon><User /></el-icon>
                  </el-avatar>
                  <span class="channel-name">{{ video.user?.username || '未知用户' }}</span>
                </div>
                <p class="description">{{ video.description }}</p>
                <div class="tags" v-if="video.tags && video.tags.length > 0">
                  <el-tag
                    v-for="tag in video.tags"
                    :key="tag"
                    size="small"
                    effect="plain"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>
        </template>

        <!-- 加载更多 -->
        <div class="load-more" v-if="hasMore && !loading">
          <el-button :loading="loadingMore" @click="loadMore">加载更多</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from '@/services/axios'
import { ElMessage } from 'element-plus'
import { VideoPlay } from '@element-plus/icons-vue'
import { formatDuration, formatViews, formatDate, formatNumber } from '@/utils/formatters'; // 导入格式化函数

import { useStore } from 'vuex' // Import useStore from vuex

const router = useRouter()
const route = useRoute()
const store = useStore() // Use vuex store


// 搜索参数
const searchQuery = computed(() => route.query.q || '')
const sortBy = ref('relevance')
const timeRange = ref('all')
const duration = ref('any')
const type = ref('all') // 暂时只支持 video
// const selectedCategories = ref([])
// const features = ref([])
const page = ref(1)
const pageSize = 10

// 状态变量
const loading = ref(false)
const loadingMore = ref(false)
const hasMore = ref(true)
const totalResults = ref(0)

// 搜索结果 (暂时只处理视频)
const results = ref([])
// const channelResults = ref([])
// const playlistResults = ref([])

// 分类选项 (如果需要)
// const categories = [...]

// 空状态描述
const emptyDescription = computed(() => {
  if (!searchQuery.value) {
    return '请输入搜索关键词'
  }
  // 暂时只处理视频
  return `未找到与"${searchQuery.value}"相关的视频`
})

// 获取搜索结果
const fetchResults = async (loadMore = false) => {
  if (!searchQuery.value) {
    results.value = []
    totalResults.value = 0
    hasMore.value = false
    return
  }

  if (loadMore) {
    loadingMore.value = true
  } else {
    loading.value = true
    page.value = 1 // 重置页码
    results.value = [] // 清空旧结果
  }

  try {
    const response = await axios.get('/api/videos/search', {
      params: {
        q: searchQuery.value,
        sortBy: sortBy.value,
        timeRange: timeRange.value,
        duration: duration.value,
        type: type.value,
        // categories: selectedCategories.value.join(','),
        // features: features.value.join(','),
        page: page.value,
        limit: pageSize,
      },
    })

    if (response.data && response.data.results) {
      const newResults = response.data.results
      if (loadMore) {
        results.value = [...results.value, ...newResults]
      } else {
        results.value = newResults
      }
      totalResults.value = response.data.totalResults || 0
      hasMore.value = results.value.length < totalResults.value
    } else {
      results.value = []
      totalResults.value = 0
      hasMore.value = false
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error(error.response?.data?.error || '搜索失败')
    if (!loadMore) {
      results.value = []
      totalResults.value = 0
      hasMore.value = false
    }
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 处理筛选条件变化
const handleFilterChange = () => {
  fetchResults()
}

// 加载更多结果
const loadMore = () => {
  if (hasMore.value && !loadingMore.value) {
    page.value++
    fetchResults(true)
  }
}

// 跳转到视频详情页
const goToVideo = (videoId) => {
  router.push({ name: 'VideoDetail', params: { id: videoId } })
}

// 监听搜索查询参数变化
watch(searchQuery, () => {
  fetchResults()
})

// 组件挂载时执行首次搜索
onMounted(() => {
  fetchResults()
})
</script>

<style scoped>
.search-container {
  padding: 20px 30px;
  max-width: 1200px;
  margin: 0 auto;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start; /* 顶部对齐 */
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.search-info h2 {
  margin: 0 0 5px 0;
  font-size: 20px;
  font-weight: 500;
}

.result-count {
  color: #606060;
  font-size: 14px;
}

.search-filters {
  display: flex;
  gap: 10px;
}

.filter-select {
  width: 130px;
}

/* 如果需要分类筛选，可以取消注释并调整样式 */
.category-select {
  margin-left: 10px; /* 向右移动一点点 */
}

.search-content {
  display: flex;
}

.search-results {
  flex: 1;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
  text-align: center;
}

.search-tips {
  margin-top: 15px;
  color: #606060;
  font-size: 14px;
  text-align: left;
  display: inline-block;
}

.search-tips ul {
  list-style: disc;
  padding-left: 20px;
  margin-top: 5px;
}

.video-results {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.video-item {
  display: flex;
  gap: 15px;
  cursor: pointer;
  padding: 10px;
  border-radius: 4px;
  transition: background-color 0.2s ease;
}

.video-item:hover {
  background-color: #f0f0f0;
}

.thumbnail {
  position: relative;
  width: 246px; /* 调整缩略图宽度 */
  height: 138px; /* 调整缩略图高度 */
  flex-shrink: 0;
  overflow: hidden;
  border-radius: 4px;
  background-color: #eee;
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.duration {
  position: absolute;
  bottom: 5px;
  right: 5px;
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 2px 4px;
  border-radius: 2px;
  font-size: 12px;
}

.video-info {
  flex: 1;
}

.title {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 8px 0;
  color: #0f0f0f;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.meta-info {
  font-size: 12px;
  color: #606060;
  margin-bottom: 8px;
}

.views-date {
  display: flex;
  align-items: center;
}

.dot {
  margin: 0 4px;
}

.channel-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #606060;
  margin-bottom: 8px;
}

.channel-name {
  font-weight: 500;
}

.description {
  font-size: 12px;
  color: #606060;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.tags {
  margin-top: 8px;
}

.tags .el-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.load-more {
  text-align: center;
  margin-top: 30px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-header {
    flex-direction: column;
    align-items: stretch;
  }

  .search-info {
    margin-bottom: 15px;
  }

  .search-filters {
    flex-wrap: wrap; /* 允许换行 */
  }

  .filter-select {
    width: calc(50% - 5px); /* 每行两个 */
  }

  .video-item {
    flex-direction: column;
  }

  .thumbnail {
    width: 100%;
    height: auto;
    padding-bottom: 56.25%; /* 16:9 宽高比 */
  }

  .thumbnail img {
    position: absolute;
    top: 0;
    left: 0;
  }
}

@media (max-width: 480px) {
  .search-container {
    padding: 15px;
  }

  .filter-select {
    width: 100%; /* 每行一个 */
  }
}
</style>